

//
//  EmoticonInputView.swift
//  自定义表情键盘
//
//  Created by YYY on 2017/9/5.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class EmoticonInputView: UIView {

    fileprivate let cellId = "cellId"
    //九宫格
    @IBOutlet weak var collectView: UICollectionView!
    //底部工具栏
    @IBOutlet weak var toolbar: EmoticonToolBar!
    
    //分页控件
    @IBOutlet weak var pageControl: UIPageControl!
    
    
    //选中表情cell的闭包回调（可选闭包）
    fileprivate var selectedEmoticonCellCallBack: ((_ emoticonModel: CPJEmoticonModel?)->())?
    
    //类方法
    class func emoticonView(selectedEmoticonCellCallBack: @escaping(_ emoticonModel: CPJEmoticonModel?)->()) -> EmoticonInputView
    {
        let nib = UINib(nibName: "EmoticonInputView", bundle: nil)
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! EmoticonInputView
        //记录闭包
        view.selectedEmoticonCellCallBack = selectedEmoticonCellCallBack
        return view
    }
    
    override func awakeFromNib() {
        
        //注册cell(原生)
        //collectView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        //注册cell（用xib加载cell）
//        let nib = UINib(nibName: "EmoticonCollectionViewCell", bundle: nil)
//        collectView.register(nib, forCellWithReuseIdentifier: cellId)
        
        //纯代码注册cell
        collectView.register(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        
        //设置toolBar代理
        toolbar.delegate = self
        
        //设置分页图片
        let bundle = EmotionManager.shared.bundle
        guard let normalImage = UIImage(named: "compose_keyboard_dot_normal", in: bundle, compatibleWith: nil),
            let selectImage = UIImage(named: "compose_keyboard_dot_selected", in: bundle, compatibleWith: nil) else
        {
            return
        }
        //使用KVC设置私有成员属性
        //用运行时查看分页控件的成员列表，使用KVC设置分页控件的图像
        pageControl.setValue(normalImage, forKey: "_pageImage")
        pageControl.setValue(selectImage, forKey: "_currentPageImage")
    }
}

//实现协议方法
extension EmoticonInputView: EmoticonToolBarDelegate
{
    func emoticonToolBarDidSelectedItemIndex(toolBar: EmoticonToolBar, index: Int)
    {
        //让collectView滚动到每个分组的第0页
        let indexPath = IndexPath(item: 0, section: index)
        collectView.scrollToItem(at: indexPath, at: .left, animated: true)
        
        //回传选中按钮索引
        toolbar.selectedIndex = index
    }
}

//MARK: UICollectionViewDelegate 代理方法
extension EmoticonInputView: UICollectionViewDelegate
{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //获取scrollView的中心点
        var center = scrollView.center
        center.x += scrollView.contentOffset.x
        
        var targetIndexPath: IndexPath?
        
        //获取当前显示cell的indexPath
        let indexPaths = collectView.indexPathsForVisibleItems
        
        for indexPath in indexPaths
        {
            //根据indexPath获得cell
            let cell = collectView.cellForItem(at: indexPath)
           
            //判断中心点位置
            if cell?.frame.contains(center) == true
            {
                targetIndexPath = indexPath
                break
            }
        }
        
        //indexPath.section对应的就是分组
        guard let target = targetIndexPath else {
            return
        }
        toolbar.selectedIndex = target.section
        
        //设置分页,不同的分组，页数不一样
        pageControl.numberOfPages = collectView.numberOfItems(inSection: target.section)
        pageControl.currentPage = target.item
        
        //使用填充图片设置颜色
//        pageControl.pageIndicatorTintColor = UIColor(patternImage: normalImage)
//        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: selectImage)
    }
}

//MARK: UICollectionViewDataSource 数据源方法
extension EmoticonInputView: UICollectionViewDataSource
{
    //分组数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        print("EmotionManager.shared.emotionsGroupArray.count: \(EmotionManager.shared.emotionsGroupArray.count)")
        return EmotionManager.shared.emotionsGroupArray.count
    }
    
    //每个分组中的表情数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return EmotionManager.shared.emotionsGroupArray[section].numberOfPages
    }
    
    //创建cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        //创建cell
        let cell = collectView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! EmoticonCollectionViewCell
        cell.emoticonsArray = EmotionManager.shared.emotionsGroupArray[indexPath.section].emoticons(page: indexPath.item)
        //设置cell代理
        cell.delegate = self
        //cell.label.text = "\(indexPath.section) \(indexPath.item)"
        
        //返回cell
        return cell
    }
}

//实现cell的代理方法
extension EmoticonInputView: EmoticonCellSelectedDelegate
{
    
    /// 选中的表情回调
    ///
    /// - Parameters:
    ///   - cell: 分页cell
    ///   - emoticonModel: 选中的表情，删除键为nil
    func emoticonCellDidSelected(cell: EmoticonCollectionViewCell, emoticonModel: CPJEmoticonModel?) {
        
        //执行闭包，回调选中的表情
        selectedEmoticonCellCallBack?(emoticonModel)
        
        //添加到最近表情
        guard let em = emoticonModel else {
            return
        }
        
        //如果当前分组是最近分组，不添加到最近表情
        let indexPath = collectView.indexPathsForVisibleItems[0]
        
        if indexPath.section == 0 {
            return
        }
        
        EmotionManager.shared.recentEmoticons(emotionModel: em)
        
        //刷新数据，第0组
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectView.reloadSections(indexSet)
    }
}
